package com.youhome.service.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.youhome.common.config.WeChatConfig;
import com.youhome.common.exception.CustomException;
import com.youhome.common.response.Result;
import com.youhome.common.response.ResultCode;
import com.youhome.service.model.BUser;
import com.youhome.service.model.UserLoginInfo;
import com.youhome.service.model.WXSession;
import com.youhome.service.service.BUserService;
import com.youhome.service.service.TokenService;
import com.youhome.service.service.WXService;
import com.youhome.utils.HttpClientUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.IOException;

/**
 * Created by chen365 on 2019/02/28.
 */
@Service
@Slf4j
public class WXServiceImpl implements WXService {
    @Autowired
    private WeChatConfig weChatConfig;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private BUserService bUserService;

    @Override
    public UserLoginInfo login(String code) throws CustomException {
        if(StringUtils.isEmpty(code)){
            throw new CustomException(ResultCode.EMPTY_CODE);
        }
        log.error("code: {}", code);
        String url = weChatConfig.getRequestUrl() + "?appid=" + weChatConfig.getAppId() + "&secret=" + weChatConfig.getAppSecret() + "&js_code=" + code + "&grant_type=" + weChatConfig.getGrantType();
        // 发送请求
        JSONObject jsonObject = HttpClientUtils.httpGet(url);
        log.debug("请求地址：{}", url);
        log.debug("请求结果：{}", jsonObject);

        if (jsonObject.getString("errcode") != null) {
            throw new CustomException(ResultCode.FAIL_LOGIN);
        }
        ObjectMapper mapper = new ObjectMapper();
        try {
            WXSession wxSession = mapper.readValue(jsonObject.toJSONString(), WXSession.class);
            String token = tokenService.createTokenByWX(wxSession);
            UserLoginInfo info = new UserLoginInfo();

            info.setToken(token);
            String openid = wxSession.getOpenid();
            BUser currentUser = bUserService.getCurrentUser(openid);
            if (currentUser != null) {
                String phone = currentUser.getPhone();
                if (!StringUtils.isEmpty(phone)) {
                    info.setPhone(phone);
                    info.setIsSignIn(true);
                }
            }
            return info;
        } catch (IOException e) {
            e.printStackTrace();
            throw new CustomException(ResultCode.ERROR);
        }
    }
}
